package 设计模式.单例模式.破坏单例模式;

import java.io.Serializable;

/**
 * @author : K k
 * @date : 21:13 2020/10/5
 */
public class Singleton implements Serializable {
    private static volatile Singleton singleton=null;
    //防止单例模式被破坏
    static boolean flag=false;

    private Singleton(){
        synchronized (Singleton.class){
            if (flag == false){
                //用于保证flag永远为true
                flag=!flag;
            }else {
                throw new RuntimeException("单例模式被侵犯！！");
            }
        }
    }

    public static Singleton getSingleton(){
        if (singleton==null){
            synchronized (Singleton.class){
                if (singleton==null){
                    singleton=new Singleton();
                }
            }
        }
        return singleton;
    }
}
